package middleware

import (
	"bytes"
	"io"
	"pids-cloud-server/logging"
	"time"

	"github.com/gin-gonic/gin"
)

// ResponseBodyWriter 是一个自定义的 ResponseWriter，用于捕获响应体
type ResponseBodyWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

// Write 重写 Write 方法，同时写入原始 writer 和缓冲区
func (r ResponseBodyWriter) Write(b []byte) (int, error) {
	r.body.Write(b)
	return r.ResponseWriter.Write(b)
}

// RequestLogger 中间件记录请求参数和响应结果
func RequestLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 开始时间
		startTime := time.Now()

		// 读取请求体
		var requestBody []byte
		if c.Request.Body != nil {
			requestBody, _ = io.ReadAll(c.Request.Body)
			// 重新设置请求体，因为读取后 body 会被消费
			c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
		}

		// 记录请求信息
		logging.Infof("[API Request] %s %s | ClientIP: %s | Headers: %v | Query: %s | Body: %s",
			c.Request.Method, c.Request.URL.Path, c.ClientIP(), c.Request.Header, c.Request.URL.RawQuery, string(requestBody))

		// 创建自定义 ResponseWriter 来捕获响应
		responseBodyWriter := &ResponseBodyWriter{
			ResponseWriter: c.Writer,
			body:           bytes.NewBufferString(""),
		}
		c.Writer = responseBodyWriter

		// 处理请求
		c.Next()

		// 计算耗时
		latency := time.Since(startTime)

		// 记录响应信息
		logging.Infof("[API Response] %s %s | Status: %d | Latency: %v | Response: %s",
			c.Request.Method, c.Request.URL.Path, c.Writer.Status(), latency, responseBodyWriter.body.String())
	}
}
